package cn.hanfeng.taskservice.controller;

import cn.hanfeng.task.taskapi.api.TaskAdminApi;
import cn.hanfeng.task.taskapi.model.CronTaskAddReq;
import cn.hanfeng.task.taskapi.model.CronTaskAddRes;
import cn.hanfeng.task.taskapi.model.CronTaskDelReq;
import cn.hanfeng.task.taskapi.model.CronTaskDelRes;
import cn.hanfeng.task.taskapi.model.CronTaskEditReq;
import cn.hanfeng.task.taskapi.model.CronTaskEditRes;
import cn.hanfeng.task.taskapi.model.Result;
import cn.hanfeng.taskservice.runnable.SchedulingRunnable;
import cn.hanfeng.taskservice.service.TaskAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author hanfeng 2020/8/27 15:51
 * @version 0.0.1
 */
@RestController
public class TaskAdminController implements TaskAdminApi {

    @Autowired
    private TaskAdminService taskAdminService;

    @Override
    public CronTaskAddRes addCronTask(@RequestBody @Valid CronTaskAddReq req) {
        String taskSign = req.getTaskSign();
        String className = req.getClassName();
        String methodName = req.getMethodName();
        String jsonParams = req.getJsonParams();
        String paramsClassType = req.getParamsClassType();

        SchedulingRunnable schedulingRunnable = new SchedulingRunnable(taskSign, className, methodName, jsonParams, paramsClassType);
        String cron = req.getCron();

        taskAdminService.addCronTask(schedulingRunnable, cron);
        CronTaskAddRes res = new CronTaskAddRes();
        res.setResult(Result.init());
        return res;
    }

    @Override
    public CronTaskEditRes editCronTask(@Valid CronTaskEditReq req) {

        String taskSign = req.getTaskSign();
        String className = req.getClassName();
        String methodName = req.getMethodName();
        String jsonParams = req.getJsonParams();
        String paramsClassType = req.getParamsClassType();

        SchedulingRunnable schedulingRunnable = new SchedulingRunnable(taskSign, className, methodName, jsonParams, paramsClassType);
        String cron = req.getCron();

        taskAdminService.editCronTask(schedulingRunnable, cron);
        CronTaskEditRes res = new CronTaskEditRes();
        res.setResult(Result.init());
        return res;
    }

    @Override
    public CronTaskDelRes delCronTask(@RequestBody @Valid CronTaskDelReq req) {
        taskAdminService.delCronTask(req.getTaskSign());
        CronTaskDelRes res = new CronTaskDelRes();
        res.setResult(Result.init());
        return res;
    }
}
